package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.model.weixin.SendMsgResult;
import cn.stylefeng.guns.sys.modular.system.model.weixin.TemplateData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 微信推送模板消息服务类
 * @author gyz
 */
@Service
public class WeChatSendTempMsgService {
    private static final Logger log= LoggerFactory.getLogger(WeChatSendTempMsgService.class);

    private static final String URL_SENDMSG="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
    private static final String TEMPID ="GvxDqRmFMg41dT9-0ndOF6oh8_XW_Vcx0mXO04m6PNQ";
    @Resource
    private DictService dictService;


    /**
     * 发送微信模板消息
     * @param openids 接受消息的openid数组
     * @param jumpUrl 需要跳转的路径
     * @param tempObj 需要传递的参数
     */
    public void sendmsg(String[] openids,String jumpUrl,JSONObject tempObj){
        //获取token
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }else{
            log.error("微信推送消息失败：‘获取token失败’");
            return;
        }

        tempObj.put("template_id",TEMPID);
        if(ToolUtil.isNotEmpty(jumpUrl)){
            tempObj.put("url",jumpUrl);
        }
        //发送消息
        for(String openid:openids){
            tempObj.put("touser",openid);
            RestTemplate rt = new RestTemplate();
            ResponseEntity<SendMsgResult> response = rt.postForEntity(URL_SENDMSG + accessToken, tempObj, SendMsgResult.class);
//            log.debug("模板推送结果：openid：{}-{}",openid,response);
            SendMsgResult result = response.getBody();
            if(result.getErrcode()!=0){
                log.error("openid：{},发送失败,cause：{}",openid,result.getErrmsg());
            }else{
                log.info("模板推送结果：openid：{}：{}",openid,result.getErrmsg());
            }
        }
    }

    /**
     *  设置模板消息参数
     * @param firststr first参数
     * @param remarkstr remark参数
     * @param keywords 多个keyword参数：keyword1，keyword2...
     * @return 返回设置的参数对象：json格式
     */
    public JSONObject setTempParam(String firststr,String remarkstr,String...keywords){
        TemplateData first = new TemplateData();
        first.setValue(firststr);
        TemplateData remark = new TemplateData();
        remark.setValue(remarkstr);
        remark.setColor("#ff0000");

        JSONObject dataObj = new JSONObject();
        dataObj.put("first",first);
        dataObj.put("remark",remark);
        for(int i=0;i<keywords.length;i++){
            TemplateData keyword = new TemplateData();
            keyword.setValue(keywords[i]);
            dataObj.put("keyword"+(i+1), keyword);
        }
        JSONObject tempObj = new JSONObject();
        tempObj.put("data",dataObj);
        return tempObj;
    }

}
